package com.example.gymnasiumsystem.servlet;

import com.example.gymnasiumsystem.dao.GymInfoDAO;
import com.example.gymnasiumsystem.dao.UserInfoDAO;
import com.example.gymnasiumsystem.enity.GymInfo;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/findGym")
public class FindGymServlet extends HttpServlet {
    private UserInfoDAO userInfoDAO=new UserInfoDAO();
    private GymInfoDAO gymInfoDAO=new GymInfoDAO();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");  // 设置请求字符编码为UTF-8
        resp.setContentType("text/html;charset=UTF-8");  // 设置响应字符编码为UTF-8
        String title=req.getParameter("gymName");
        GymInfo gymInfo=gymInfoDAO.getGymByName(title);
        List<GymInfo> gymInfos=new ArrayList<>();
        gymInfos.add(gymInfo);
        if (gymInfo == null) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("没有您要找的活动");
            return;
        }
        String acceptHeader = req.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.contains("application/json")) {
            // 设置响应内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 将活动数据转换为 JSON 格式并写入响应
            Gson gson = new Gson();
            String json = gson.toJson(new ActivityResponse(gymInfos));
            resp.getWriter().write(json);
        } else {
            // 否则，返回 HTML 页面（转发给 JSP）
            resp.sendRedirect("admin/gymList.jsp");
        }

    }
    private static class ActivityResponse {
        private List<GymInfo> gymInfos;

        public ActivityResponse(List<GymInfo> gymInfos) {
            this.gymInfos = gymInfos;
        }

        public List<GymInfo> getActivities() {
            return gymInfos;
        }
    }

}
